package com.fzy.springsecurity.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fzy.springsecurity.bean.TUser;
import com.fzy.springsecurity.mapper.TUserMapper;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import java.util.List;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * @author fzy
 * @version 1.0
 * 创建时间：2024-10-04 14:01
 */

@Configuration
public class WebSecurityConfig {

    @Resource
    private TUserMapper tUserMapper;

    @Bean
    public UserDetailsService userDetailsService(){
        return username -> {
            TUser one = tUserMapper.selectOne(Wrappers.lambdaQuery(TUser.class).eq(TUser::getName, username));
            if (one == null) throw new UsernameNotFoundException("用户名未注册");
            return new org.springframework.security.core.userdetails.User(
                    one.getName(),
                    one.getPassword(),
                    one.getIsEnabled() == 1,   // 账户是否可用
                    true,  //账户是否过期
                    true,  //密码是否过期
                    true,  //账户是否被锁定
                    List.of(() -> "ROLE_USER")  //权限
            );
        };
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorize -> authorize  // 开启授权保护
                        .anyRequest()       // 对所有请求进行保护
                        .authenticated()    // 对已认证的用户进行自动授权
                )
                .formLogin(form ->{
                    form.loginPage("/login").permitAll() // 自定义登录页面，并放行
                            .usernameParameter("username")  // 配置自定义的的表单用户名和密码参数名
                            .passwordParameter("password")
                            .failureUrl("/login?error")  // 登录失败后跳转的页面
                            .successHandler(new MyAuthenticationSuccessHandler())  // 认证成功处理
                            .failureHandler(new MyAuthenticationFailureHandler())  // 认证失败处理
                            ;
                })
                .logout(logout ->{
                    logout.logoutSuccessHandler(new MyLogoutSuccessHandler());  // 注销成功处理
                })
                .exceptionHandling(exception ->{
                    exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());  // 未认证处理
                })
                .cors(withDefaults())     // 开启跨域
                .csrf(c -> c.disable())   // 关闭csrf
                ;
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
